<template>
  <div class="app-container">
    <div class="step">
      <div class="step-title">
        <el-steps :active="active" align-center finish-status="success">
          <el-step title="基本资料"></el-step>
          <el-step title="个人信息"></el-step>
          <el-step title="确认信息"></el-step>
        </el-steps>
      </div>
      <div class="step-btm">
        <div class="change" v-if="active == 0 || active == 2">
          <!-- <p>
            <span>编码</span>
            <input v-model="tempData.code" :disabled="active == 2" type="text" placeholder="请输入编码" />
          </p> -->
          <p>
            <span>姓名</span>
            <el-input v-model="tempData.username" :disabled="active == 2" type="text" class="userselect" placeholder="请输入姓名" />
          </p>
          <p>
            <span>所属部门</span>
            <el-select v-model="tempData.departments" :disabled="active == 2" placeholder="请选择所属部门" class="userselect">
              <el-option
                v-for="item in bumenList"
                :key="item.id"
                :label="item.departments"
                :value="item.departments"
              ></el-option>
            </el-select>
          </p>
          <p>
            <span>性别</span>
						<el-radio v-model="tempData.sex" label="男" :disabled="active == 2">男</el-radio>
						<el-radio v-model="tempData.sex" label="女" :disabled="active == 2">女</el-radio>
          </p>
          <p>
            <span>职务</span>
						<el-select v-model="tempData.power" placeholder="请选择职务" :disabled="active == 2" class="userselect">
						  <el-option
						    v-for="item in options"
						    :key="item.value"
						    :label="item.value"
						    :value="item.value"
						  ></el-option>
						</el-select>
            <!-- <input v-model="tempData.power" :disabled="active == 2" type="text" placeholder="请输入职务" /> -->
          </p>
					<p>
					  <span>角色分配</span>
					  <el-select v-model="roles" multiple placeholder="请选择角色" :disabled="active == 2" class="userselect">
					    <el-option
					      v-for="item in roleArr"
					      :key="item.roleId"
					      :label="item.roleDescribe"
					      :value="item.roleId"
					    ></el-option>
					  </el-select>
					</p>
          <p>
            <span>手机号码</span>
            <el-input v-model="tempData.phone" :disabled="active == 2" type="text" class="userselect" placeholder="请输入手机号码" />
          </p>
          <p>
            <span>邮箱</span>
            <el-input v-model="tempData.email" :disabled="active == 2" type="text" class="userselect" placeholder="请输入邮箱" />
          </p>
          <p>
            <span>头像</span>
            <el-upload
              class="avatar-uploader"
              action=""
							:http-request="designUpAvatar"
              :show-file-list="false"
							:disabled="active == 2"
            >
              <img v-if="tempData.icon" :src="tempData.icon" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </p>
        </div>
        <div class="fileup" v-if="active == 1 || active == 2" v-for="(item,index) in fileNum" :key="index">
          <p>
            <span>资料名</span>
            <el-input v-model="item.filename" :disabled="active == 2" class="userselect" type="text" placeholder="请输入您要上传的资料名" />
          </p>
          <p>
            <span>上传资料</span>
            <el-upload
              class="upload-demo"
              drag
							:data="index"
							:show-file-list="false"
              :http-request="designUpFile"
              action=""
							:multiple='false'
							:disabled="active == 2"
              >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
						<p style="margin: 0;">
							<strong v-if="item.filePath">{{item.filename}}</strong>
							<strong v-if="item.filePath" @click="downLoad(item.filePath)">下载<i class="el-icon-download" /></strong>
						</p>
          </p>
        </div>
        <h6 class="addfile" @click="addfile" v-if="active == 1">新增</h6>
      </div>
      <div class="submits">
        <div class="save" @click="prev" v-if="active != 0">上一步</div> 
        <div class="save" @click="next" v-if="active < 2">下一步</div>
        <div class="save" @click="save" v-else>确认信息</div>
        <div class="nosave" @click="nosave">取消</div>
      </div>
    </div>
  </div>
</template>

<script>
import { updatePeople,addPeople,addUser,updateUser,uploadFile,getBumen,getUserFiles,getRole,userContactRole } from '@/api/people'
let user = null
export default {
  data() {
    return {
      active: 0,
      imageUrl: "",
      writeOradd: 1,  //0修改还是1添加
      tempData: {},
      content: '',  //文件命名
      roles: [],
			fileNum: [{
				filename: '',
				filePath: ''
			}],   //需要上传的文件个数
      //filePath: '',  //文件上传成功返回的路径
			bumenList: [],
			roleArr: [],
			options: [{
				value: '董事长'
			},{
				value: '总经理'
			},{
				value: '总监'
			},{
				value: '部长'
			},{
				value: '员工'
			}],
      value: null
    };
  },
  mounted() {
    console.log(this.$route.params)
		this.getbumens()
    this.getRoleList()
    if(this.$route.params.options){
      this.tempData = JSON.parse(this.$route.params.options)
      this.writeOradd = 0
      user = this.tempData.userId
      this.roles = this.tempData.roleList.map(item => item.roleId)
      console.log(this.tempData)
			this.getUserfile(this.tempData.userId)
    } else {
      this.writeOradd = 1
      this.tempData = {
        departments: '',
        email: '',
        icon: '',
        phone: '',
        power: '',
        username: '',
				sex: '男'
      }
    }
  },
  methods: {
		// 上一步下一步
    next() {
      if((/^1(3|4|5|6|7|8|9)\d{9}$/.test(this.tempData.phone))){
        if(this.tempData.username){
          if(this.tempData.power){
            if(this.roles && this.roles.length){
              if(this.active == 0){
                this.writeUser()
              }
              if (this.active++ > 2) {
                this.active = 0;
              }
            }else{
              this.$message({
                message: '请选择角色！',
                type:'warning'
              })
            }
          }else{
            this.$message({
              message: '请选择职务！',
              type:'warning'
            })
          }
        }else{
          this.$message({
            message: '请填写姓名！',
            type:'warning'
          })
        }
      }else{
        this.$message({
          message: '请填写正确的手机号！',
          type:'warning'
        })
      }
    },
    prev() {
      if (this.active-- < 1) {
        this.active = 0;
      }
    },
		// 获取用户文档信息
		getUserfile(id){
			getUserFiles({userId: id}).then(res => {
				console.log(res)
				if(res.data.list.length != 0){
					this.fileNum = []
					res.data.list.map(item => {
						this.fileNum.push({
							filename: item.fileDescribe,
							filePath: item.fileName
						})
					})
				}
			})
		},
		downLoad(filepath){
			window.location.href = filepath
		},
		// 获取用户角色信息
		getRoleList() {
		  getRole({}).then(res => {
		    console.log('rolelist',res)
		    this.roleArr = res.data
		  })
		},
		// 新增用户资料
    addfile(){
      this.fileNum.push({
				filename: ''
			})
    },
    save() {
			this.$router.push({
				name: 'Personnel'
			})
		},
		// 获取部门列表
		getbumens(){
			getBumen({}).then(res => {
				console.log(res)
				this.bumenList = res.data
			})
		},
		// 编辑用户信息(新增修改)
		writeUser(){
      console.log('roles',this.roles)
      // 根据选择角色身份，重构角色身份
      let rolelist = []
      this.roleArr.map(item => {
        this.roles.map(list => {
          if(list === item.roleId){
            rolelist.push({
              roleDescribe: item.roleDescribe,
              roleId: item.roleId,
              roleName: item.roleName
            })
          }
        })
      })
      // 根据所选部门，获取公司id
      const bumen = this.bumenList.filter(item => item.departments = this.tempData.departments)[0]
      console.log('部门',bumen)
      console.log('rolelist',rolelist)
      console.log('writeOradd',this.writeOradd)
      this.tempData.gongsi = bumen.parentId
      this.tempData.roleList = rolelist
			if(this.writeOradd == 1){
				addUser(this.tempData).then(res => {
					console.log(res)
					user = res.data.userId
					// userContactRole({
					// 	roleId: this.tempData.roleId,
					// 	userId: user,
					// }).then(result => {
					// 	console.log('用户关联角色',res)
					// })
				})
			}else{
				updateUser(this.tempData).then(res => {
					console.log(res)
					// userContactRole({
					// 	roleId: this.tempData.roleId,
					// 	userId: user,
					// }).then(result => {
					// 	console.log('用户关联角色',res)
					// })
				}) 
			}
		},
    nosave() {
			this.$router.go(-1)
		},
		// 上传头像
		designUpAvatar(item){
			console.log(this.fileNum)
      var formData = new FormData()
      const loading = this.$loading({
        lock: true,
        text: '上传中请稍等...',
        spinner: 'el-icon-loading',
        background: 'rgba(255, 255, 255, 0.8)'
      })
			formData.append("file", item.file)
			uploadFile(formData).then(res => {
			  console.log(res)
				this.$message({
				  showClose: true,
				  message: '添加成功',
				  type: "success"
        })
        loading.close()
				this.imageUrl = res
				this.tempData.icon = res
			})
		},
		// 上传文件
    designUpFile(item) {
			console.log(this.fileNum)
      var formData = new FormData();
      formData.append("file", item.file)
      formData.append('content', this.fileNum[item.data].filename)
      uploadFile(formData).then(res => {
        console.log('res',res)
				this.fileNum[item.data].filePath = res
				console.log(this.fileNum)
				console.log('user',user)
				this.$forceUpdate()
        addPeople({
					fileName: res,
					fileDescribe: this.fileNum[item.data].filename,
					userId: user
				}).then(res => {
          console.log(res)
          this.$message({
            showClose: true,
            message: '添加成功',
            type: "success"
          })
        })
      })
    },
    // 头像上穿成功
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style lang="scss" scoped>
// .app-container{
//   background: #fff;
// }
.step {
  padding: 20px;
  background: #fff;
}
.disable{
	background: #808080 !important;
	pointer-events: none;
}
.addfile{
  width: 80px;
  height: 32px;
  text-align: center;
  line-height: 32px;
  color: #fff;
  font-size: 14px;
  border-radius: 4px;
  margin-left: 30px;
  background: #18a05e;
  cursor: pointer;
  font-size: 14px;
  font-weight: 100;
  margin: 0px 100px;
}
.change {
  display: flex;
  flex-wrap: wrap;
  background: #fff;
  border-radius: 8px;
  padding: 20px 0;
  > p {
    width: 33%;
    font-size: 14px;
    display: flex;
    align-items: center;
    color: #333;
    /deep/.el-input__inner {
      // width: inherit;
      background: none;
      height: 32px;
      // line-height: 32px;
      color: #333;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding: 0 25px;
    }
    /deep/.el-input__icon {
      line-height: 32px;
    }
    .userselect {
      // max-width: 250px;
      flex: 1;
    }

    > span {
      display: block;
      width: 100px;
      text-align: right;
      padding-right: 15px;
    }
    > input {
      width: inherit;
      flex: 1;
      height: 32px;
      border-radius: 3px;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding-left: 10px;
      color: #333;
    }
  }
}
.submits {
  display: flex;
  padding: 20px 20px 0 20px;
	margin-top: 20px;
	border-top: 1px solid #ccc;
  justify-content: flex-end;
  align-items: center;
  > div {
    width: 80px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    color: #fff;
    font-size: 14px;
    border-radius: 4px;
    margin-left: 30px;
    cursor: pointer;
  }
  .save {
    background: #18a05e;
  }
  .nosave {
    background: #999;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #999 !important;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
	border: 1px dashed #CCCCCC;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.fileup{
  padding: 20px 0;
  display: flex;
  flex-wrap: wrap;
  // align-items: center;
  flex-direction: column;
  // justify-content: center;
  > p {
    width: 50%;
    font-size: 14px;
    display: flex;
		flex-wrap: wrap;
    align-items: center;
    color: #333;
    /deep/.el-input__inner {
      // width: inherit;
      background: none;
      height: 32px;
      // line-height: 32px;
      color: #333;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding: 0 25px;
    }
    /deep/.el-input__icon {
      line-height: 32px;
    }
    /deep/.el-upload-dragger {
			width: 100%;
      height: 100px;
    }
    /deep/.el-upload-dragger .el-icon-upload {
      font-size: 60px;
      color: #C0C4CC;
      margin: 0; 
      line-height: 1;
			width: 100%;
    }
		/deep/.el-upload {
			width: 100%;
		}
    .userselect {
      // max-width: 250px;
      flex: 1;
    }

    > span {
      display: block;
      width: 100px;
      text-align: right;
      padding-right: 15px;
    }
    > input {
      width: inherit;
      flex: 1;
      height: 32px;
      border-radius: 3px;
      border: 1px solid rgba(0, 0, 0, 0.1);
      padding-left: 10px;
      color: #333;
    }
		>strong{
			display: inline-block;
			padding-left: 100px;
			font-weight: 100;
			font-size: 14px;
			&:last-child{
				cursor: pointer;
				color: #13ce66;
				font-weight: 600;
			}
		}
    >div{
      width: inherit;
      flex: 1;
    }
  }
}
</style>